package cn.yuyiling.jelly.srai.service.impl;

import cn.yuyiling.jelly.kgai.config.LLMConfigManager;
import cn.yuyiling.jelly.qa.api.AnswerService;
import cn.yuyiling.jelly.qa.api.QuestionService;
import cn.yuyiling.jelly.qa.mongodb.entity.Answer;
import cn.yuyiling.jelly.qa.mongodb.entity.Question;
import cn.yuyiling.jelly.qa.mongodb.repository.AnswerRepository;
import cn.yuyiling.jelly.qa.mongodb.repository.QuestionRepository;
import cn.yuyiling.jelly.sr.api.LearningProgressService;
import cn.yuyiling.jelly.sr.mongodb.entity.UserLearningRecord;
import cn.yuyiling.jelly.srai.api.RecommendationAdviceService;
import cn.yuyiling.jelly.srai.mongodb.entity.RecommendationAdvice;
import cn.yuyiling.jelly.srai.mongodb.repository.RecommendationAdviceRepository;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@DubboService
public class RecommendationAdviceServiceImpl implements RecommendationAdviceService {
    @DubboReference
    private LearningProgressService learningProgressService;
    @Autowired
    private RecommendationAdviceRepository recommendationAdviceRepository;
    @DubboReference
    private AnswerService answerService;
    @DubboReference
    private QuestionService questionService;

    private final ChatClient chatClient;

    public RecommendationAdviceServiceImpl(ChatModel chatModel) {
        LLMConfigManager configManager = new LLMConfigManager();
        String model = configManager.getModel();
        String token = configManager.getToken();
        int timeout = configManager.getTimeout();
        String defaultSystem = configManager.getDefaultSystem();
        this.chatClient = ChatClient.builder(chatModel)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withModel(model)
                                .build()
                )
                .defaultSystem(defaultSystem)
                .build();

    }

    @Override
    public String generateRecommendationForUser(String userId) {
        List<UserLearningRecord> records = learningProgressService.findByUserId(userId);

        // 提取最近10次错题记录
        List<UserLearningRecord> recentWrongAnswers = records.stream()
                .filter(record -> record.getQuizResult() != null && record.getQuizResult().getScore() < 60)
                .sorted((r1, r2) -> r2.getCreatedAt().compareTo(r1.getCreatedAt()))
                .limit(10)
                .collect(Collectors.toList());

        // 构建Prompt输入
        String prompt = buildPrompt(recentWrongAnswers);

        String response = chatClient.prompt()
                .user(prompt)
                .call()
                .content();

        // 保存建议到数据库
        RecommendationAdvice advice = new RecommendationAdvice();
        advice.setUserId(userId);
        advice.setAiAdvice(response);
        advice.setCreatedAt(LocalDateTime.now());
        recommendationAdviceRepository.save(advice);

        return response;
    }

    private String buildPrompt(List<UserLearningRecord> wrongAnswers) {
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("以下是用户最近的错题信息，请给出300字以内的具体改进建议。\n");
        promptBuilder.append("要求：\n");
        promptBuilder.append("- 包含至少一个可操作的具体措施\n");
        promptBuilder.append("- 使用中文输出\n");

        promptBuilder.append("【最近10次错题】:\n");
        for (int i = 0; i < wrongAnswers.size(); i++) {
            String answerId = wrongAnswers.get(i).getQuizResult().getAnswerId();
            Answer answer = answerService.getAnswerById(answerId);
            String questionId = answer.getParentId();
            Question question = questionService.getQuestionById(questionId);
            promptBuilder.append("【问题" + (i + 1) + "】:\n");
            promptBuilder.append(question.getContent().getText() + "\n");
            promptBuilder.append("【答案" + (i + 1) + "】:\n");
            promptBuilder.append(answer.getContent().getText() + "\n");
        }

        promptBuilder.append("\n请生成建议：");

        return promptBuilder.toString();
    }
}